package com.zp.common.base.utils;

import com.zp.common.base.dao.AuthRepository;
import com.zp.common.base.dao.RoleAuthRepository;
import com.zp.common.base.dao.RoleRepository;
import com.zp.common.base.entity.AuthInfo;
import com.zp.common.base.entity.RoleAuth;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.zp.common.base.constant.Atom.CONSTANT_ONE;

@Component
@RequiredArgsConstructor
public class AuthorizationUtils {

    private final RoleRepository roleRepository;
    private final RoleAuthRepository roleAuthRepository;
    private final AuthRepository authRepository;
    /**
     * 获取拥有url的角色集合
     * @param url url
     * @return
     */
    public List<String> listRoles(String url){
        //auth->id
        AuthInfo auth = authRepository.findByUrlAndStatus(url,CONSTANT_ONE);
        //role_auth->roleId
        if (Objects.nonNull(auth)){
            List<RoleAuth> roleAuths = roleAuthRepository.findByAuthIdAndStatus(auth.getId(), CONSTANT_ONE);
            if (!CollectionUtils.isEmpty(roleAuths)){
                List<String> roles=new ArrayList<>();
                //role->roles
                roleAuths.forEach(param-> roles.add(roleRepository.selectById(param.getRoleId()).getName()));
                return roles;
            }
        }
        return null;
    }
}
